<template>
	<view class="Login">
		<u-toast ref="uToast"></u-toast>
		<u-code :seconds="seconds" @end="codeDis = false;" @start="codeDis = true;" ref="uCode" @change="codeChange"></u-code>
		<u-modal :title="agreeList[agreeIndex].title" :show="agreeShow" @confirm="agreeShow = false;" confirmText="我已阅读">
			<view class="slot-content">
				<view class="modal_scroll">
					<u-parse :content="agreeList[agreeIndex].content"></u-parse>
				</view>
			</view>
		</u-modal>
		<u-navbar :auto-back="true" :leftIcon="leftIcon" title=" " :placeholder="true" bg-color="transparent"></u-navbar>
		<image class="login_bg" mode="widthFix" src="/static/loginbg.jpg"></image>
		<view class="login_box">
			<view class="login_logo">
				<u-image width="108rpx" height="108rpx" radius="12rpx" :src="mainBaseUrl + '/assets/xcx/logo.png'"></u-image>
				<view class="login_title">欢迎使用中青趣游</view>
			</view>
			<view class="login_main">
				<view class="login_tip">
					<view>请输入您的手机号码，</view>
					<view>登录或者注册您的账号</view>
				</view>
				<u-form labelPosition="top" :model="form" :rules="rules" ref="uForm" :errorType="errorType"
					labelWidth="200rpx">
					<view class="login_form">
						<u-form-item label="账号" prop="username" borderBottom>
							<u-input v-model="form.username" type="number" border="none" placeholder="请输入手机号"></u-input>
						</u-form-item>
						<!-- #ifdef H5 -->
						<u-form-item label="邀请码" prop="invitation" borderBottom>
							<u-input readonly v-model="form.invitation" border="none" placeholder="请输入邀请码"></u-input>
						</u-form-item>
						<!-- #endif -->
						<u-form-item label="验证码" prop="code" borderBottom>
							<u-input v-model="form.code" border="none" placeholder="请输入验证码"></u-input>
							<u-button throttleTime="1000" slot="right" @click="getCode" :text="tips" :customStyle="codeBtn" color="#0FBCF9" shape="circle" :disabled="codeDis"></u-button>
						</u-form-item>
					</view>
					<view class="flex_box login_agree">
						<view @click="agreeStatus = !agreeStatus;" class="flex_box login_agree_main">
							<view class="login_agree_dot"></view>
							<u-checkbox-group>
								<u-checkbox size="24rpx" :checked="agreeStatus" activeColor="#0FBCF9" shape="circle"></u-checkbox>
							</u-checkbox-group>
							<view class="login_agree_text">阅读并同意<text @tap.stop="showAgree(0)">《用户协议》</text>和<text @tap.stop="showAgree(1)">《隐私权政策》</text></view>
						</view>
					</view>
					<view class="login_btn">
						<u-button throttleTime="1000" color="#45B9A2" shape="circle" :customStyle="btnStyle" @click="submit" text="开始"></u-button>
					</view>
					<!-- #ifdef MP-WEIXIN -->
					<view class="login_btn">
						<u-button throttleTime="1000" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" :custom-style="{height: '88rpx'}" shape="circle" color="#28c445" text="手机号一键登录"></u-button>
					</view>
					<!-- #endif -->
					<!-- <u-divider line-color="#45B9A2" text-color="#45B9A2" text="第三方登录"></u-divider>
					<view class="flex_box flex_row_center">
						<u-image width="68rpx" height="68rpx" src="/static/wx.png" @click="wxLogin"></u-image>
					</view> -->
				</u-form>
			</view>
			<!-- #ifdef H5 -->
			<view @click="$goUrl('/pages/login/download/download','to')" class="login_down">已有账号，下载App</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import { checkUpdate } from '@/components/yzhua006-update/js/app-update-check.js';
	import { login, sendCode , wxLoginAndRegister , wxLoginbinding, getAbout, getVersion, getInfo} from '@/common/http.api.js';
	let that;
	export default {
		data() {
			return {
				leftIcon: 'close',
				form: {
					username: '',
					code: "",
					invitation: "",
				},
				errorType: "toast",
				rules: {
					username: [{
							type: 'string',
							required: true,
							message: '请输入您的手机号',
							trigger: ['blur', 'change']
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								return uni.$u.test.mobile(value);
							},
							message: '您输入的手机号不正确',
							trigger: ['change', 'blur'],
						}
					],
					code: [{
							type: 'string',
							required: true,
							message: '请输入您的验证码',
							trigger: ['blur', 'change']
						},
					],
				},
				btnStyle: {
					height: '88rpx',
				},
				codeBtn: {
					width: '188rpx',
					height: '58rpx',
				},
				tips: '',
				seconds: 60,
				codeDis: false,
				agreeStatus: false,
				agreeIndex: 0,
				agreeShow: false,
				agreeList: [
					{
						title: "用户协议",
						content: "用户协议内容"
					},
					{
						title: "隐私权政策",
						content: "隐私权政策内容"
					}
				]
			}
		},
		onLoad(options) {
			that = this;
			if (options.scene) {
				let scene = decodeURIComponent(options.scene).split(','),params={}
				scene.forEach((item,index)=>{
					let param = item.split('=')
					params[param[0]] = param[1]
				})
				if(params.invitation) {
					that.$u.vuex("invitation",params.invitation)
				}
			}
			if (options.invitation) {
				that.$u.vuex("invitation",options.invitation);
			}
			that.leftIcon = uni.$u.pages().length == 1 ? ' ' : 'close'
			that.getAbout()
		},
		onShow() {
			if(that.invitation) that.form.invitation = that.invitation
			// #ifdef APP-PLUS
			that.getAppInfo(0);
			// #endif
		},
		onReady() {
			that.$refs.uForm.setRules(that.rules);
		},
		methods: {
			//获取线上APP版本信息
			getAppInfo(type) {
				const system_info = uni.getSystemInfoSync();
				let params = {
					os: system_info.platform //本机设备操作系统  （android || ios）
				};
				if (params.os != 'ios' && params.os != 'android') false; //如果不是安卓或ios 返回false
			
				//这里自行请求API获取版本信息 建议传入操作系统标识，返回本机对应的操作系统最新版本信息，也就是安卓的返回就是安卓的版本信息  ios返回就是ios的版本信息
				getVersion()
					.then(res => {
						let versionInfo = res.data;
						let update_info = {
							version: params.os == 'ios' ? versionInfo.ios_new : versionInfo.newversion, //线上版本
							now_url: params.os == 'ios' ? versionInfo.ios_dn_url : versionInfo.downloadurl, //更新链接
							silent: versionInfo.silent ? versionInfo.silent : 0, //是否是静默更新
							force: versionInfo.enforce, //是否是强制更新
							net_check: versionInfo.net_check ? versionInfo.net_check : 1, //非WIfi是否提示
							note: versionInfo.content //更新内容
						};
						checkUpdate(update_info, type).then(res => {
							if (res.msg) {
								// plus.nativeUI.toast(res.msg);
							}
						}); ///检查更新
						//checkUpdate 这个方法会做什么？：线上版本号 与 本地版本号做对比 ，如果需要更新  根据静默，强制、wifi等信息执行静默更新或跳转到升级页面
						//跳转升级页面的前提是，需要新建并在pages.json中配置升级页面，配置方法请查看插件详情
					})
					.catch(err => {
						uni.$u.toast(err.msg);
					});
			},
			getAbout() {
				getAbout()
					.then(res => {
						that.info = res.data;
						that.agreeList[0].content = res.data.agreement;
						that.agreeList[1].content = res.data.privacy;
					})
					.catch(err => {
						uni.$u.toast(err.msg);
					});
			},
			getUserInfo(e){
				console.log(e)
			},
			submit() {
				that.$refs.uForm.validate().then(async res => {
					if(!that.agreeStatus){
						uni.$u.toast('请阅读并同意登录协议');
						return;
					}
					// // #ifdef MP-WEIXIN
					// let codeInfo = await wx.login()
					// that.form.user_code = codeInfo.code
					// // #endif
					login(that.form).then(res=>{
						uni.$u.vuex("loginInfo", res.data.userinfo);
						getInfo()
							.then(res => {
								if (res.code == 1) {
									uni.$u.vuex('userInfo', res.data);
									uni.setStorageSync('loginStatus', 2);
									if(that.shareInfo){
										let shareInfo = {
											title: that.shareInfo.title, // 默认为小程序名称
											path: `/pages/home/index/index?invitation=${that.userInfo.invitation}`, // 默认为当前页面路径
											imageUrl: that.shareInfo.imageUrl
										}
										that.$u.vuex('shareInfo',shareInfo)
										uni.$u.mpShare = shareInfo
									}
								} else {
									uni.$u.toast(res.msg);
								}
							})
							.catch(err => {});
						that.$refs.uToast.show({
							type: "success",
							message: "登录成功",
							complete(){
								if(uni.$u.pages().length == 1){
									// #ifdef H5
									that.$goUrl('/pages/login/download/download','to')
									// #endif
									// #ifdef APP-PLUS || MP-WEIXIN
									uni.switchTab({
										url: '/pages/home/index/index'
									})
									// #endif
								}else{
									uni.navigateBack()
								}
							}
						});
					}).catch(err=>{
						uni.$u.toast(err.msg);
					});
				}).catch(errors => {

				})
			},
			// 获取验证码
			codeChange(text) {
				that.tips = text;
			},
			getCode() {
				if(that.form.username==''){
					uni.$u.toast('请输入您的手机号');
					return;
				}
				if(!uni.$u.test.mobile(that.form.username)){
					uni.$u.toast('您输入的手机号不正确');
					return;
				}
				if(that.$refs.uCode.canGetCode) {
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					});
					sendCode({mobile: that.form.username}).then(res=>{
						uni.hideLoading();
						uni.$u.toast('验证码已发送');
						that.$refs.uCode.start();
					}).catch(err=>{
						uni.$u.toast(err.msg);
					});
				} else {
					uni.$u.toast('倒计时结束后再发送');
				}
			},
			// 切换登录方式
			changeType(){
				that.form.type = that.form.type == 1 ? 2 : 1;
				that.$refs.uCode.reset(),that.tips = '获取验证码',that.codeDis = false,that.form.code = '',that.form.password = '';
			},
			// 查看协议
			showAgree(e){
				that.agreeIndex = e,that.agreeShow = true;
			},
			wxLogin(){
				if(!that.agreeStatus){
					uni.$u.toast('请阅读并同意登录协议');
					return;
				}
				let aweixin = null;
				plus.oauth.getServices(function(services){
				    services.forEach((item)=>{
				        if(item.id=='weixin'){
				            aweixin = item;
				        }
				    })
					//没有取得微信登陆的服务
				    if(!aweixin){uni.$u.toast('当前环境不支持微信登录');return;}
				    if(!aweixin.authResult){
						//是否登录认证过
				        aweixin.authorize((e)=>{
							wxLoginAndRegister({code: e.code}).then(res=>{
								uni.$u.vuex("loginInfo", res.data.userinfo);
								if(res.data && res.data.userinfo  && res.data.userinfo.mobile){
									//已绑定手机
									uni.setStorageSync("loginStatus", 2);
									that.$refs.uToast.show({
										type: "success",
										message: "登录成功",
										complete(){
											that.$goUrl("/pages/home/index/index","tab");
										}
									});
								}else{
									//去绑定手机
									that.$goUrl('/pages/login/bindPhone/bindPhone','to');
								}
							}).catch((err)=>{
								uni.$u.toast(err.msg);
							})
				        },(e)=>{
						  uni.$u.toast('用户取消授权');
				        },{scope:'snsapi_userinfo',state:''})
				    }else{
						uni.$u.toast('请使用其他登录方式');
				    }
				}, function(e){
					uni.$u.toast('获取登录授权服务列表失败');
				});
			},
			getPhoneNumber(e){
				if(!e.detail.code){
					return
				}
				login({phone_code: e.detail.code}).then(res=>{
					uni.$u.vuex("loginInfo", res.data.userinfo);
					getInfo()
						.then(res => {
							if (res.code == 1) {
								uni.$u.vuex('userInfo', res.data);
								uni.setStorageSync("loginStatus", 2);
								if(that.shareInfo){
									let shareInfo = {
										title: that.shareInfo.title, // 默认为小程序名称
										path: `/pages/home/index/index?invitation=${that.userInfo.invitation}`, // 默认为当前页面路径
										imageUrl: that.shareInfo.imageUrl
									}
									that.$u.vuex('shareInfo',shareInfo)
									uni.$u.mpShare = shareInfo
								}
							} else {
								uni.$u.toast(res.msg);
							}
						})
						.catch(err => {});
					that.$refs.uToast.show({
						type: "success",
						message: "登录成功",
						complete(){
							if(uni.$u.pages().length == 1){
								uni.switchTab({
									url: '/pages/home/index/index'
								})
							}else{
								uni.navigateBack()
							}
						}
					});
				}).catch(err=>{
					uni.$u.toast(err.msg);
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.Login {
		min-height: 100vh;
		background-color: #F6F8FA;
		.login_bg{
			width: 100%;
			position: absolute;
			top: 0;
			left: 0;
		}
		.login_box {
			position: relative;
			z-index: 2;
			padding: 0 36rpx;
			.login_logo{
				padding: 24rpx 36rpx;
				.login_title {
					font-size: 28rpx;
					font-weight: bold;
					color: #ffffff;
					line-height: 88rpx;
				}
			}
			.login_main{
				background: linear-gradient(180deg, #ccdcfe 0%, #FFFFFF 75%);
				border-radius: 36rpx;
				padding: 80rpx 36rpx;
				.login_tip{
					font-size: 40rpx;
					color: #1E272E;
					font-weight: bold;
					line-height: 60rpx;
					margin-bottom: 60rpx;
				}
				.login_form ::v-deep {
					.u-form-item__body__left__content__label{
						font-weight: 500;
						color: #1E272E;
						font-size: 32rpx;
						padding: 20rpx 0;
					}
					.uni-input-input{
						font-weight: bold;
						color: #1E272E;
						font-size: 32rpx;
					}
					.uni-input-placeholder{
						font-weight: 500;
						color: #D2DAE2;
						font-size: 32rpx;
					}
					.u-line{
						border-bottom: 2rpx solid #1E272E !important;
					}
				}
			}
			.login_agree{
				padding: 40rpx 0 60rpx;
				.login_agree_main{
					position: relative;
					.login_agree_dot{
						position: absolute;
						top: 0;
						left: 0;
						z-index: 2;
						width: 40rpx;
						height: 40rpx;
					}
					.login_agree_text{
						font-size: 26rpx;
						text{
							color: #0FBCF9;
						}
					}
				}
			}
			.login_down{
				font-size: 28rpx;
				color: #1E272E;
				font-weight: 500;
				width: 360rpx;
				height: 60rpx;
				line-height: 60rpx;
				margin: 20rpx auto 40rpx;
				text-align: center;
				cursor: pointer;
			}
			.login_btn{
				margin-bottom: 30rpx;
			}
		}
		.modal_scroll{
			max-height: 720rpx;
			overflow-y: scroll;
		}
	}
</style>
